define(function(require, exports, module) {

	var $ = require('jquery');
	require('../util/jquery.icheck');
	require('jbox');
	require('../util/tinymce-admin-page.js');
	require('artTemplate/artTemplate/2.0.1/template.js');
	require('jquery/jquery-form/1.0.0/jquery.form.js');
	require('jquery/jquery-json/2.4.0/jquery.json.js');
	require('jquery/jquery-cookie/1.3.1/jquery.cookie.js');
	require('seajs/seajs/2.1.1/sea.js');
	require('spin/1.3/spin.js');

	require('jquery/jquery-file-upload/8.8.5/vendor/jquery.ui.widget.js');
	require('jquery/jquery-file-upload/8.8.5/jquery.iframe-transport.js');
	require('jquery/jquery-file-upload/8.8.5/jquery.fileupload.js');
	var List = require('../util/list');
	require('../util/charCount');

	var cg = $("#startPid").val();// 草稿id
	var uid = "";
	var roles = '';
	var projectId = '';
	var n = '';
	var fundTarget='';
	var comp='';


	if($.trim(g_user.login) == 'true'){
		uid = ''+g_user.id;
	}else{
		uid = '-1';
	}
	//console.log(uid);
	if(uid=="-1"){
		var submit = function (v, h, f) {
		    if (v == 'ok')
		    	window.location.href=$CONFIG.base_url +"/login";
		};
		$.jBox.confirm("登录超时，请点击确定重新登录？", "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
	}

	//获取页面地址参数
	exports.getParam = function(path,name) {
		var value = path.substr(path.lastIndexOf('?') + 1);
		var  reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)","i");
		var param = value.match(reg);
		if (param != null) return param[2]; 
		return null;
	};

	var path = decodeURIComponent(window.location.href);
	var pid= exports.getParam(path,"pid");
	projectId = pid;
	$("#startPid").val(pid);

	
	//选择活动类别
	$("#open-select").on("click",".open-item",function(){
		$(".open-item").removeClass('active');
		$(this).addClass('active');
		$("#openCategory").val($(this).attr("value"));
	});
		
	module.exports = List;
	function List() {
		this.options = [];
	}
	;
	exports.options = {
		listLink : '',
		listParams : '',
		pageLink : '',
		pageParams : ''
	};

	if ($.trim(g_user.login) == 'true') {
		uid = '' + g_user.id;
		// 获取用户信息
		exports.options.userlink = $CONFIG.base_url + "/api/user";
		exports.options.userParams = {
			"uid" : uid
		};
		var userInfor = $.get(exports.options.userlink,
				exports.options.userParams);
		userInfor.done(function(data) {
			roles = data.user.roles;
			$("#user_id").attr("value",data.user.id);
		});
	} else {
		uid = '-1';
	}
	
	
	// 加载活动分类
	var getting = $.get($CONFIG.base_url + "/api/system/project/categorylist",{"type":2});
	getting.done(function(data) {
		data={"data":data};
		var html = template.render("open-select-template", data);
		$("#open-select").empty().append(html);
		$('.open-group input').iCheck({
			radioClass : 'iradio_minimal-yellow',
			increaseArea : '-10%', // optional
		});
	});
		
	// 获取项目详情
	exports.loadProject = function(projectId) {
		exports.options.projectLink = $CONFIG.base_url + "/api/preferential/get";
		exports.options.projectParams = {
			"uid" : uid,
			"id" : projectId
		};
		var commentList = $.get(exports.options.projectLink,
				exports.options.projectParams);
		commentList.done(function(data) {	
			// 加载编辑器
			tinymce.init({
				selector : 'textarea#activityBackground',
				theme : "modern",
				plugins : [ "preview image table contextmenu",
				            "emoticons paste textcolor"],
				            toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
				            toolbar2: "print preview media | forecolor backcolor emoticons",
				language : 'zh_CN',
				file_browser_callback : function(field_name, url, type, win) {
					if (type == 'image') {
						$('#fileupload').click();
					}
				},
				init_instance_callback:load,
			});
			$("#name").val(data.name);	
			$("#status").val(data.status);	
			$('.open-item[value="'+ data.projectCategory.id +'"]').click();
			$("#description").text(data.description);
			function load(){
				console.log($("#activityBackground_ifr").contents().find("#tinymce"));
				$("#activityBackground_ifr").contents().find("#tinymce").html(data.activityBackground);
			}
			var img_id = data.photoUrl.substr(data.photoUrl.lastIndexOf("/")+1);
			$("#coverId").val(img_id);
			$("#coverId-preview").append("<img>")
			$("#coverId-preview img").attr("src", data.photoUrl+"/170x100/");


			if (data.projectCategory.id != "") {
				var a = data.projectCategory.id-1;
				a="checkf" + a;
				$("#open-select span").each(function() {
					var check = $(this).attr("class");
					if (a == check) {
						$(this).click();
					}
				});
				
			}
			if (data.user.gender == "1") {
				$("#label-man").click();
			} else {
				$("#label-woman").click();
			}
		});
	};
	
	// 加载编辑器
	tinymce.init({
		selector : 'textarea#activityBackground',
		theme : "modern",
		plugins : [ "preview image table contextmenu",
		            "emoticons paste textcolor"],
		            toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
		            toolbar2: "print preview media | forecolor backcolor emoticons",
		language : 'zh_CN',
		file_browser_callback : function(field_name, url, type, win) {
			if (type == 'image') {
				$('#fileupload').click();
			}
		},
	});
	
	// 上传图片
	exports.fileUpload = function fileUpload(e, v, a, s) {
		$("#" + a).fileupload(
				{
					url : $CONFIG.base_url + e,
					dataType : 'json',
					formData : {
						uid : g_user.id
					},
				 add: function (e, data) {
				        var goUpload = true;
				        var uploadFile = data.files[0];
				        if (!(/\.(gif|jpg|jpeg|png)$/i).test(uploadFile.name)) {
				        	$.jBox.tip('亲~请选择正确的图片格式');
				            goUpload = false;
				        }
				        if (uploadFile.size > 1048576) { // 1mb
				        	$.jBox.tip('亲~图片太大了，最大不超过1mb哦！');
				            goUpload = false;
				        }
				        if (goUpload == true) {
				            data.submit();
				        }
				    },
				    progressall : function(e, data) {
						var progress = parseInt(data.loaded / data.total * 100,10);
						$("#loading-load").show();
						$("#loading-load").text(progress + '%');
					},
					done : function(e, data) {
						 var result = data.result[0].body ? data.result[0].body.innerHTML : data.result;
						$.each(result, function(index, file) {
							var html = '<img src="' + $CONFIG.base_url
									+ '/common/attachment/download/' + file.id
									+ '/170x100"/>';
							if (s == "file-input") {
								$('#' + v).val(file.id);
								$('.' + v + "-name").text(file.fileName);
								$('#' + v + "-preview").empty().append(html);
								$("#loading-load").hide();
							} else {
								$('#' + s).empty().append(html);
								$('#' + v).val(file.id);
								$("#loading-load").hide();
							}
						});
					}
				});
	};

	// 加载预览
	exports.loadYuLan = function(e) {
		$("#yl").remove();
		$("#startProjectSubmit").parent()
				.after(
						"<td><input id='yl' type='button' class='raise-submit' value='预览活动'/></td>");
		$("#yl").click(
				function() {
					window.open($CONFIG.base_url + "/project/preferential/preview?id=" + e
							+ "", "_blank");
				});
	};

	// 提交表单
	exports.submitForm = function submitForm(e, v, callback) {
		var ed = '';
		if (v == "/api/preferential/add") {
			ed = tinyMCE.get('activityBackground').getContent();
			backGround=ed.replace('<table','<table border="1px solid" width="100%"');
			$("#activityBackground").val(backGround);
		}
		var json = form2js(e, '.', true);
		var postData = $.toJSON(json);
		postData["user"] = {"id":uid};
		console.log(postData);
		$.ajax({
			url : $CONFIG.base_url + v,
			type : "POST",
			data : postData,
			// dataType : "json",
			contentType : "application/json",
			success : function(data) {
				/*if (v == "/api/preferential/add") {
					projectId = data.id;
					$("#pid").val(projectId);
					exports.changeProjectStatus(data);
					$(".t2").click();
				}*/
				if (typeof (callback) == "function") {
					callback();
				}
				
			},
			error : function() {
				$.jBox.tip('亲~出问题啦，请再试一次！');
			}
		});
	};
	
	// 发起服务
	$("#startProjectSubmit").click(function(e) {
		e.preventDefault();
		if(uid=="-1"){
			var submit = function (v, h, f) {
			    if (v == 'ok')
			    	window.location.href=$CONFIG.base_url +"/login";
			};
			$.jBox.confirm("登录超时，请点击确定重新登录？", "<span style='text-align:center;width:100%;display:block;color: #834313;'><span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span></span>", submit);
			return;
		}		
		var vald='';
		$("#startProjectForm .required").each(function(){
			if($(this).val()==""){
				vald=$(this).attr("id");
			}
		});
		if(vald!=""){
			switch(vald){
			case "name":
				$.jBox.tip("亲~活动名称不能为空哦！");
				$("#"+vald).focus();
				return;
				break;
			default:
			}
		}
		if ($("#coverId").val() == "") {
			$.jBox.tip("亲～您还没有上传图片哦");
			return;
		}
		bg = tinyMCE.get('activityBackground').getContent();
		if (bg == "") {
			$.jBox.tip("亲～您还没有填写活动详情哦");
			return;
		}
		if(bg.length>15000){
			$.jBox.tip("亲~活动详情建议不要超过1500字！");
			return;
		}
			
		$.jBox.tip("<span style='text-align:center;width:100%;display:block;color: #834313;'>正在努力提交，请稍后...</span>","loading");
		exports.submitForm("panel-308006", "/api/preferential/add", function() {
			$.jBox.tip('亲~发起成功！');
			setTimeout(function(){window.location.href=$CONFIG.base_url + '/'+$CONFIG.admin_url+'/manage/preferential/list';},1000);
		});
	});

	// 修改服务
	$("#editProjectSubmit").click(function() {
		if(uid=="-1"){
			var submit = function (v, h, f) {
			    if (v == 'ok')
			    	window.location.href=$CONFIG.base_url +"/login";
			};
			$.jBox.confirm("登录超时，请点击确定重新登录？", "<span style='text-align:center;width:100%;display:block;color: #834313;'><span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span></span>", submit);
			return;
		}		
		var vald='';
		$("#startProjectForm .required").each(function(){
			if($(this).val()==""){
				vald=$(this).attr("id");
			}
		});
		if(vald!=""){
			switch(vald){
			case "name":
				$.jBox.tip("亲~活动名称不能为空哦！");
				$("#"+vald).focus();
				return;
				break;
			default:
			}
		}
		if ($("#coverId").val() == "") {
			$.jBox.tip("亲～您还没有上传图片哦");
			return;
		}
		bg = tinyMCE.get('activityBackground').getContent();
		if (bg == "") {
			$.jBox.tip("亲～您还没有填写活动详情哦");
			return;
		}
		if(bg.length>15000){
			$.jBox.tip("亲~活动详情建议不要超过1500字！");
			return;
		}
			
		$.jBox.tip("<span style='text-align:center;width:100%;display:block;color: #834313;'>正在努力提交，请稍后...</span>","loading");
		exports.submitForm("panel-308006", "/api/preferential/add", function() {
			$.jBox.tip('亲~修改成功！');
			setTimeout(function(){window.location.href=$CONFIG.base_url + '/'+$CONFIG.admin_url+'/manage/preferential/list';},1000);
		});
	});
	
	// 检测输入字数
	exports.checkCount = function() {
		$("#name").charCount({
			allowed : 30,
			warning : 5
		});
		$("#address").charCount({
			allowed : 100,
			warning : 10
		});
		$("#description").charCount({
			allowed : 200,
			warning : 10
		});
		$("#activityContent").charCount({
			allowed : 500,
			warning : 50
		});
	};
	exports.checkCount();

	$("#file-input").click(function() {
		v = "coverId";
		a = $(this).attr("id");
		s = "file-input";
		exports.fileUpload("/common/attachment/upload/multi", v, a, s);
	});

	// 二次编辑
	if(pid != null &&uid!="-1") {
		$("#pid").val(pid);
		projectId=pid;
			$(".project_id").val(projectId);
			exports.loadYuLan(projectId);
			exports.loadProject(projectId);
			$("#startProjectSubmit").hide();
			$("#editProjectSubmit").show();
	}
});
